package com.peanut.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.peanut.model.ResourceTreeNode;
import com.peanut.model.Resource;
import com.peanut.persistence.ResourceMapper;

/**
 * 资源管理类
 * @author Johan.Chenjh
 *
 * 2011-3-14
 */
@Service
public class ResourceService {
	private ResourceMapper resourceMapper;

	@Autowired
	public void setResourceManager(ResourceMapper resourceMapper) {
		this.resourceMapper = resourceMapper;
	}
	
	public List<Resource> queryAllModules(String type) {
		return resourceMapper.queryAllModules(type);
	}
	
	/* (non-Javadoc)
	 * @see com.peanut.service.ResourceManager#queryTopResource()
	 */
	public List<Resource> queryTopResource(String name) {
		return resourceMapper.queryTopResource(name);
	}
	
	/* (non-Javadoc)
	 * @see com.peanut.service.ResourceManager#removeNodeAndChildren(java.lang.Integer)
	 */
	public void removeNodeAndChildren(Integer moduleId) {
		resourceMapper.removeNodeAndChildren(moduleId);
	}

	/* (non-Javadoc)
	 * @see com.peanut.service.ResourceManager#queryByUserId(java.lang.String)
	 */
	public List<Resource> queryTopResourceByAccount(String account) {
		return resourceMapper.queryTopResourceByAccount(account);
	}
	
	public List<Resource> querySubResourceByAccount(Map param) {
		return resourceMapper.querySubResourceByAccount(param);
	}
	
	public List<HashMap<String, String>> queryUrlResourceWithRole(String param) {
		return resourceMapper.queryUrlResourceWithRole(param);
	}
	
	public List<ResourceTreeNode> createSubResourceTreeByAccount(Map param) {
		List<Resource> subResourceList = resourceMapper.querySubResourceByAccount(param);
		List<ResourceTreeNode> resutlTree = makeCompanyTree(subResourceList);
		return resutlTree;
	}
	
	private List<ResourceTreeNode> makeCompanyTree(List<Resource> subResourceList) {
		List<ResourceTreeNode> treeList = new ArrayList<ResourceTreeNode>();
		for (Resource module : subResourceList) {
			ResourceTreeNode treeNode = new ResourceTreeNode();
			treeNode.setId(module.getId());
			treeNode.setAction(module.getAction());
			treeNode.setText("<font size='2'>"+module.getName()+"</font>");
			treeNode.setDescription(module.getDescription());
			treeNode.setParentId(treeNode.getId());
			treeNode.setEnabled(module.getEnabled());
			treeNode.setIsDisplay(module.getIsDisplay());
			treeNode.setName(module.getName());
			treeNode.setType(module.getType());
			treeNode.setOrderNumber(module.getOrderNumber());
			treeNode.setOpenView(module.getOpenView());
			treeNode.setLeaf(BooleanUtils.toBoolean(module.getIsleaf()));
			treeList.add(treeNode);
		}
		return treeList;
	}
}
